#include "bsp.h"
#include "lcd.h"


void setLcdPower(FunctionalState status) {
	if(status) {
		HAL_GPIO_WritePin(LCD_VCC_GPIO_Port, LCD_VCC_Pin, GPIO_PIN_RESET);
	} else {
		HAL_GPIO_WritePin(LCD_VCC_GPIO_Port, LCD_VCC_Pin, GPIO_PIN_SET);
	}
}


void setLedPower(FunctionalState status) {
	if(status) {
		HAL_GPIO_WritePin(LEDEN_GPIO_Port, LEDEN_Pin, GPIO_PIN_RESET);
	} else {
		HAL_GPIO_WritePin(LEDEN_GPIO_Port, LEDEN_Pin, GPIO_PIN_SET);
	}
}


void ledFlash3(void) {
	setLedPower(1);
	HAL_Delay(100);
	setLedPower(0);
	HAL_Delay(100);
	setLedPower(1);
	HAL_Delay(100);
	setLedPower(0);
	HAL_Delay(100);
	setLedPower(1);
	HAL_Delay(100);
	setLedPower(0);
	HAL_Delay(100);
	
}


extern DAC_HandleTypeDef hdac;
uint32_t dacData = 0;

/*********************************************************************************
  *Description：  	set led idd current by mA.
  *Input:  			mA value
  *Output:  
  *Return:  
  *Others:  
**********************************************************************************/

uint8_t ledCurrent = 0;
#define I_LED_MAX  10
#define I_LED_MIN  0

void setLedCurrent(uint8_t current) {
	ledCurrent = current;
	
	HAL_DAC_Start(&hdac, DAC_CHANNEL_1);
	
	if( HAL_DAC_GetState(&hdac) == HAL_DAC_STATE_READY) {
					
		HAL_DAC_SetValue(&hdac, DAC_CHANNEL_1, DAC_ALIGN_12B_R, current * 100.0 * 4.095 / 1.1);
	}
}

void ledCurrentAdd(void) {
	if (ledCurrent < I_LED_MAX) {
		ledCurrent++;
		setLedCurrent(ledCurrent);
	}
}

void ledCurrentDec(void) {
	if (ledCurrent > I_LED_MIN) {
		ledCurrent--;
		setLedCurrent(ledCurrent);
	}
}




void test_keyExti(void) {
	//HAL_GPIO_TogglePin(LCD_VCC_GPIO_Port, LCD_VCC_Pin);
}




MODE mode = MODE_CONTRAST;

void key1Work(void) {
	if (mode == MODE_CONTRAST) {
		if (isLcdTransfering() == 0) {
			__contrast_add();
		}
	}	
}

void key2Work(void) {
	if (mode == MODE_CONTRAST) {
		if (isLcdTransfering() == 0) {
			toggleLcdPause();
		}
	}	
}

void key3Work(void) {
	if (mode == MODE_CONTRAST) {
		if (isLcdTransfering() == 0) {
			__contrast_dec();
		}
	}	
}

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
	switch(GPIO_Pin) {
		case KEY1_Pin:
			
			if(	HAL_GPIO_ReadPin(KEY2_GPIO_Port, KEY2_Pin) == GPIO_PIN_RESET ) {
				//ledFlash3();	
				//HAL_GPIO_TogglePin(LEDEN_GPIO_Port, LEDEN_Pin);
				ledCurrentAdd();
			} else {
				key1Work();
			}
		break;
		
		case KEY2_Pin:
			key2Work();
		break;
		
		case KEY3_Pin:
			if(	HAL_GPIO_ReadPin(KEY2_GPIO_Port, KEY2_Pin) == GPIO_PIN_RESET ) {
				//ledFlash3();	
				//HAL_GPIO_TogglePin(LEDEN_GPIO_Port, LEDEN_Pin);
				ledCurrentDec();
			} else {
				key3Work();
			}			
		break;
		
		default: 
			break;
	}
}



#ifdef DEBUG
void test_setLcdPower(void) {
	while(1) {
		HAL_Delay(1000);
		setLcdPower(ENABLE);
		HAL_Delay(1000);
		setLcdPower(DISABLE);
	}
}
#endif 


